package com.luxsoft.sw3.cfd.crypto;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.StringReader;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;

import org.apache.commons.lang.ArrayUtils;


public class GenSig2 {
	
	public static final String CADENA_ORIGINAL="AQUI ESTA EL CONTENIDO DEL CFD ";
	
	public static void main(String[] args) {
		
		try{
        	KeyPairGenerator keyGen=KeyPairGenerator.getInstance("DSA","SUN");
        	SecureRandom random=SecureRandom.getInstance("SHA1PRNG", "SUN");
        	keyGen.initialize(1024, random);
        	KeyPair keyPar=keyGen.generateKeyPair();
        	PrivateKey priv=keyPar.getPrivate();
        	PublicKey pub=keyPar.getPublic();
        	
        	Signature dsa=Signature.getInstance("SHA1withDSA","SUN");
        	dsa.initSign(priv);
        	ByteArrayInputStream fis = new ByteArrayInputStream(CADENA_ORIGINAL.getBytes());
        	BufferedInputStream bufin = new BufferedInputStream(fis);
        	byte[] buffer = new byte[1024];
        	int len;
        	while ((len = bufin.read(buffer)) >= 0) {
        	    dsa.update(buffer, 0, len);
        	};
        	bufin.close();

        	byte[] realSig = dsa.sign();
        	
        	System.out.println("Signed: "+ArrayUtils.toString(realSig));
        	
        	//Save de signature
        	FileOutputStream sigfos=new FileOutputStream("C:\\sw3\\cfd\\sig2");
        	sigfos.write(realSig);
        	sigfos.close();
        	
        	//Save the public key in a file
        	byte[] key=pub.getEncoded();
        	FileOutputStream keyfos=new FileOutputStream("C:\\sw3\\cfd\\suepk2.key");
        	keyfos.write(key);
        	keyfos.close();

        	
        } catch (Exception e) {
            System.err.println("Caught exception " + e.toString());
        }

	}

}
